package com.fenghuajueli.module_user.model;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData.PAY_SUCCESS;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.FlowLiveDataConversions;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.fenghuajueli.lib_paysdk.AliPayUtils;
import com.fenghuajueli.lib_paysdk.WXPayUtils;
import com.fenghuajueli.lib_statistics.UmEventConstant;
import com.fenghuajueli.lib_statistics.UmEventUtils;
import com.fenghuajueli.libbasecoreui.BaseApplication;
import com.fenghuajueli.libbasecoreui.baseswitch.SwitchKeyUtils;
import com.fenghuajueli.libbasecoreui.constants.AppConfigInfo;
import com.fenghuajueli.libbasecoreui.constants.EventBusConstants;
import com.fenghuajueli.libbasecoreui.constants.SwitchKeyConstants;
import com.fenghuajueli.libbasecoreui.data.entity.eventbus.EventEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsData;
import com.fenghuajueli.libbasecoreui.data.entity.goods.GoodsEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.SignStatusEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.WeChatPayInfoEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.ZfbPayInfoEntity;
import com.fenghuajueli.libbasecoreui.data.entity.goods.ZfbSubscribeVipEntity;
import com.fenghuajueli.libbasecoreui.data.entity.user.UserInfoEntity;
import com.fenghuajueli.libbasecoreui.listener.BaseCallBackListener;
import com.fenghuajueli.libbasecoreui.listener.TokenErrorBackListener;
import com.fenghuajueli.libbasecoreui.user.UserInfoUtils;
import com.fenghuajueli.libbasecoreui.utils.CommonUtils;
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils;
import com.fenghuajueli.libbasecoreui.utils.RouteUtils;
import com.fenghuajueli.libbasecoreui.viewmodel.BaseViewModel;
import com.fenghuajueli.libbasecoreui.viewmodel.data.OtherCodeData;
import com.fenghuajueli.module_route.UserModuleRoute;
import com.fenghuajueli.module_user.constants.H5PayInfoEntity;
import com.fenghuajueli.module_user.constants.PayConstant;
import com.fenghuajueli.module_user.listener.UploadCallback;
import com.fenghuajueli.module_user.network.repository.TemplateRepository;
import com.fenghuajueli.module_user.network.result.TemplateResult;
import com.fenghuajueli.module_user.utils.GoodsPriceUtil;
import com.fenghuajueli.module_user.utils.ZfbSubscribeCheckUtil;
import com.ijianji.lib_onekeylogin.OneKeyLoginUtils;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 用户组件模块由于页面不多，所有的网络请求接口都放在一个model里进行处理 复用
 */
public class UserViewModel extends BaseViewModel {

    public LiveData<TemplateResult> templateResult = FlowLiveDataConversions.asLiveData(TemplateRepository.getTemplateData());

    /**
     * 商品列表数据
     */
    public MutableLiveData<List<GoodsEntity>> goodsList = new MutableLiveData<>();

    /**
     * 检测用户是否处于签约中的状态值
     */
    public MutableLiveData<SignStatusEntity> signStatus = new MutableLiveData<>();

    /**
     * 用户注册成功的数据值，如果需要在界面观察是否注册成功，则使用这个值
     */
    public MutableLiveData<UserInfoEntity> registerSuccess = new MutableLiveData<>();

    /**
     * 用户检测用户手机号是否注册的数据观察者
     */
    public MutableLiveData<Boolean> phoneIsRegister = new MutableLiveData<>();

    /**
     * 验证码倒计时可用数据观察者
     */
    public MutableLiveData<Integer> verificationCodeTime = new MutableLiveData<>();

    /**
     * 密码修改成功的数据观察者
     */
    public MutableLiveData<UserInfoEntity> editPasswordSuccess = new MutableLiveData<>();

    /**
     * 用户信息获取成功的数据观察者
     */
    public MutableLiveData<UserInfoEntity> userInfoGetSuccess = new MutableLiveData<>();

    /**
     * 一键登录阿里云认证成功过后，返回的accesstoken
     */
    public MutableLiveData<String> oneKeyLoginAuthSuccess = new MutableLiveData<>();

    /**
     * H5订单号
     */
    public MutableLiveData<String> h5OrderId = new MutableLiveData<>();

    public MutableLiveData<Boolean> isH5pay = new MutableLiveData<>();
    public MutableLiveData<Boolean> payOrder = new MutableLiveData<>();

    /**
     * 一键登录工具类
     */
    private OneKeyLoginUtils oneKeyLoginUtils;

    /**
     * 微信小程序支付的id
     */
    private String wechatMiniAppPayId = "";

    /**
     * 注册回调
     */
    private UploadCallback uploadCallback = null;

    public void getGoodsList(LifecycleOwner owner) {
        RequestInfoModel.getGoodsList(owner, "token", true, false, new TokenErrorBackListener<GoodsData>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(GoodsData data) {
                hideLoading();
                if (data != null && data.getList() != null && data.getList().size() > 0) {
                    wechatMiniAppPayId = data.getSqb_xcx_id();
                    goodsList.postValue(data.getList());
                } else {
                    showToast("VIP商品获取失败！");
                    finishActivity();
                }

            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading();
            }
        });
    }

    /**
     * 获取次数商品
     *
     * @param owner
     */
    public void getTimesGoodsList(LifecycleOwner owner) {
        String token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
        if (TextUtils.isEmpty(token)) {
            showToast("Token无效");
            handlerTokenError();
            return;
        }
        RequestInfoModel.getTimesGoodsList(owner, token, "1", true, new TokenErrorBackListener<GoodsData>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(GoodsData data) {
                hideLoading();
                if (data != null && data.getList() != null && data.getList().size() > 0) {
                    wechatMiniAppPayId = data.getSqb_xcx_id();
                    goodsList.postValue(data.getList());
                } else {
                    showToast("VIP商品获取失败！");
                    finishActivity();
                }

            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading();
            }
        });
    }

    public void goZfbPay(Activity activity, GoodsEntity goodsEntity, String token) {
        if (!CommonUtils.checkAliPayInstalled(activity)) {
            showToast("请先安装支付宝客户端！");
            return;
        }

        RequestInfoModel.getZfbOrder((LifecycleOwner) activity, token, "2", goodsEntity.getId() + "",
                new TokenErrorBackListener<ZfbPayInfoEntity>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(ZfbPayInfoEntity data) {
                        //下单成功
                        AliPayUtils.getInstance().pay(activity, data.getOrder_string(),
                                true, new AliPayUtils.AlipayCallBack() {
                                    @Override
                                    public void callBack(AliPayUtils.PayResult resultSet) {
                                        hideLoading();
                                        if (resultSet.getResultStatus().equals("9000")) {
                                            //支付成功
                                            BaseApplication.getApplication().onPay(goodsEntity.getGoods_price());
                                            PayConstant.goPay = false;
                                            otherStatusData.postValue(new OtherCodeData(PAY_SUCCESS));
                                            showToast("会员开通成功，现在可以去使用啦！");
                                        } else if (resultSet.getResultStatus().equals("6001")) {
                                            PayConstant.pay = 0;
                                            showToast("支付取消");
                                        } else {
                                            showToast("支付失败");
                                        }
                                    }
                                });
                    }

                    @Override
                    public void onFailed(String error) {
                        showToast(error);
                        hideLoading();
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading();
                    }
                });
    }


    /**
     * 微信下单支付
     *
     * @param activity
     * @param currentGood
     */
    public void goWxPay(Activity activity, GoodsEntity currentGood, String token) {
        GoodsPriceUtil.goodsPrice = currentGood.getGoods_price();
        if (SwitchKeyUtils.getWechatPayType() == SwitchKeyConstants.WECHAT_PAY_TYPE_MINI_APP) {
            if (TextUtils.isEmpty(wechatMiniAppPayId)) {
                handlerNormalWxPay(activity, currentGood, token);
            } else {
                String appId = AppConfigInfo.WECHAT_APP_ID; // 填移动应用(App)的 AppId，非小程序的 AppID
                IWXAPI api = WXAPIFactory.createWXAPI(activity, appId);
                WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                String appid = "ANDROID_" + AppUtils.getAppPackageName();
                req.userName = wechatMiniAppPayId; // 填小程序原始id
                req.path = "/pages/pay/pay?channel=" + AppConfigInfo.PAY_CHANNEL_WECHAT + "&goods_id=" + currentGood.getId()
                        + "&goods_type=1&host=" + AppConfigInfo.getWechatMiniPayHost() + "&token=" + token + "&app_id="
                        + appid + "&coupon_id=" + "&market_channel=" + RequestInfoModel.getMarketChannel() + "&env=" + (AppUtils.isAppDebug() ? "test" : "prod");
                req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
                api.sendReq(req);
            }
        } else if (SwitchKeyUtils.getWechatPayType() == SwitchKeyConstants.WECHAT_PAY_TYPE_NORMAL) {
            handlerNormalWxPay(activity, currentGood, token);
        } else if (SwitchKeyUtils.getWechatPayType() == SwitchKeyConstants.WECHAT_PAY_TYPE_H5) {
            //采用H5支付
            handlerH5Pay(activity, currentGood, token);
        } else {
            //默认用微信app的支付方式
            handlerNormalWxPay(activity, currentGood, token);
        }
    }

    private void handlerH5Pay(Activity activity, GoodsEntity currentGood, String token) {
        RequestInfoModel.getH5Order((LifecycleOwner) activity, token, "18", currentGood.getId() + "",
                new TokenErrorBackListener<H5PayInfoEntity>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(H5PayInfoEntity data) {
                        //下单成功
                        hideLoading();
                        if (data != null) {
                            h5OrderId.postValue(data.getOrder_no());
                            handleH5Pay(data.getH5_url(), data.getReferer());
                        } else {
                            showToast("下单失败!");
                        }

                    }

                    @Override
                    public void onFailed(String error) {
                        showToast(error);
                        hideLoading();
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading();
                    }
                });
    }

    private void handlerNormalWxPay(Activity activity, GoodsEntity currentGood, String token) {
        RequestInfoModel.getWechatOrder((LifecycleOwner) activity, token, "1", currentGood.getId() + "",
                new TokenErrorBackListener<WeChatPayInfoEntity>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(WeChatPayInfoEntity data) {
                        //下单成功
                        WXPayUtils.WXPayBuilder wxPayBuilder = new WXPayUtils.WXPayBuilder()
                                .setAppId(data.getAppid())
                                .setNonceStr(data.getNoncestr())
                                .setPackageValue("Sign=WXpay")
                                .setPartnerId(data.getPartnerid())
                                .setPrepayId(data.getPrepayid())
                                .setSign(data.getSign())
                                .setTimeStamp(String.valueOf(data.getTimestamp()));
                        WXPayUtils wxPayUtils = wxPayBuilder.build();
                        wxPayUtils.toWXPayNotSign(activity);
                    }

                    @Override
                    public void onFailed(String error) {
                        showToast(error);
                        hideLoading();
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading();
                    }
                });
    }

    /**
     * 支付成功之后刷新用户的信息
     *
     * @param currentGood
     */
    public void updateUserInfo(LifecycleOwner owner, GoodsEntity currentGood) {
        RequestInfoModel.getUserInfo(owner, "", new TokenErrorBackListener<UserInfoEntity.UserInfoBean>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(UserInfoEntity.UserInfoBean data) {
                hideLoading();
                try {
                    if (data != null) {
                        if (data.getVip_info().getVip_type() > 0) {
                            LogUtils.d("后台已经收到支付成功回调：" + data.getVip_info().getVip_type());
                            UserInfoEntity userInfoEntity = UserInfoUtils.getInstance().getUserInfoEntity();
                            if (null == userInfoEntity) {
                                userInfoEntity = new UserInfoEntity();
                                userInfoEntity.setToken(RequestInfoModel.bindUserToken);
                            }
                            userInfoEntity.setUserInfo(data);
                            UserInfoUtils.getInstance().setUserInfoEntity(userInfoEntity);
                            UserInfoUtils.getInstance().saveUserInfoToLocal(UserInfoUtils.getInstance().getUserInfoEntity());
                            EventBus.getDefault().post(new EventEntity(EventBusConstants.UPDATE_USER_INFO, null));
                        }
                    }
                    UserInfoUtils.getInstance().checkOrBindPhone();
                } catch (Exception e) {
                    LogUtils.e("回调错误：" + e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading();
            }
        });
        otherStatusData.postValue(new OtherCodeData(OtherCodeData.UPDATE_USER_INFO));
    }


    /**
     * 支付宝订阅类型  先签约后付款的模式
     */
    public static final int ZFB_SUB_TO_PAY = 1;

    /**
     * 支付宝订阅类型  先付款后签约的模式
     */
    public static final int ZFB_PAY_TO_SUB = 2;


    /**
     * 支付宝订阅类商品下单
     *
     * @param activity
     * @param goodsEntity
     */
    public void preZfbSubscribeOrder(Activity activity, GoodsEntity goodsEntity, String token) {
        if (!CommonUtils.checkAliPayInstalled(activity)) {
            showToast("请先安装支付宝客户端！");
            return;
        }

        RequestInfoModel.getZfbSubscribeVipParams((LifecycleOwner) activity, token, goodsEntity.getId() + "",
                new TokenErrorBackListener<ZfbSubscribeVipEntity>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(ZfbSubscribeVipEntity data) {
                        if (goodsEntity.getVip_type() > 100) {
                            if (goodsEntity.getSub_type() == ZFB_PAY_TO_SUB) {
                                //先扣款后签约的模式   因为前面有多余的参数，需要截取
                                if (TextUtils.isEmpty(data.getOrder_string())) {
                                    showToast("参数异常，下单失败！");
                                    hideLoading();
                                } else {
                                    String orderInfo = data.getOrder_string().
                                            substring(data.getOrder_string().indexOf("?") + 1);
                                    AliPayUtils.getInstance().pay(activity, orderInfo,
                                            true, new AliPayUtils.AlipayCallBack() {
                                                @Override
                                                public void callBack(AliPayUtils.PayResult resultSet) {
                                                    hideLoading();
                                                    if (resultSet.getResultStatus().equals("9000")) {
                                                        //支付成功
                                                        BaseApplication.getApplication().onPay(goodsEntity.getGoods_price());
                                                        PayConstant.goPay = false;
                                                        otherStatusData.postValue(new OtherCodeData(PAY_SUCCESS));
                                                        showToast("会员开通成功，现在可以去使用啦！");
                                                    } else if (resultSet.getResultStatus().equals("6001")) {
                                                        PayConstant.pay = 0;
                                                        showToast("支付取消");
                                                    } else {
                                                        showToast("支付失败");
                                                    }
                                                }
                                            });
                                }
                            } else {
                                //默认 0 和1都是先签约后代扣的模式
                                boolean isSuccess = ZfbSubscribeCheckUtil.goSubscribeVip(activity, data.getPage_url());
                                if (!isSuccess) {
                                    showToast("启动支付宝支付失败！请重试");
                                }
                                hideLoading();
                            }
                        }
                    }

                    @Override
                    public void onFailed(String error) {
                        showToast(error);
                        hideLoading();
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading();
                    }
                });
    }


    /**
     * 检测当前用户是否处于支付宝签约状态中
     */
    public void checkIsSubscribeZfbActive(Activity activity, GoodsEntity goodsEntity, String payChannel) {
        filterH5Handle(payChannel);
        if (MmkvUtils.get(RequestInfoModel.LOGIN_OUT, false)) {
            if (UserInfoUtils.getInstance().isLogin()) {
                String token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
                if (TextUtils.isEmpty(token)) {
                    showToast("Token无效");
                    handlerTokenError();
                } else {
                    checkIsSubscribeZfbActiveWithToken(activity, goodsEntity, payChannel, token);
                }
            } else {
                hideLoading();
                ARouter.getInstance().build(UserModuleRoute.USER_LOGIN)
                        .withString("type", "needToVip")
                        .navigation();
            }
            return;
        }

        if (UserInfoUtils.getInstance().isLogin()) {
            String token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
            if (TextUtils.isEmpty(token)) {
                showToast("Token无效");
                handlerTokenError();
            } else {
                checkIsSubscribeZfbActiveWithToken(activity, goodsEntity, payChannel, token);
            }
        } else {
            RequestInfoModel.getVisitorBindUserToken(new BaseCallBackListener<String>() {
                @Override
                public void onSuccess(String data) {
                    checkIsSubscribeZfbActiveWithToken(activity, goodsEntity, payChannel, data);
                }

                @Override
                public void onFailed(String error) {
                    //这里继续执行下单逻辑
                    if (AppConfigInfo.PAY_CHANNEL_ZFB.equals(payChannel)) {
                        handlerZfbPay(activity, goodsEntity, RequestInfoModel.visitorToken);
                    } else if (AppConfigInfo.PAY_CHANNEL_WECHAT.equals(payChannel)) {
                        handlerWxPay(activity, goodsEntity, RequestInfoModel.visitorToken);
                    }
                }

                @Override
                public void onHandlerStart() {

                }
            });
        }
    }

    private void checkIsSubscribeZfbActiveWithToken(Activity activity, GoodsEntity goodsEntity, String payChannel, String token) {
        RequestInfoModel.checkZfbSubscribeSignStatus((LifecycleOwner) activity, token,
                new TokenErrorBackListener<SignStatusEntity>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(SignStatusEntity data) {
                        hideLoading();
                        if (data.getStatus() == 1) {
                            showToast("您已是订阅会员，取消订阅后可购买其他会员");
                        } else {
                            //这里继续执行下单逻辑
                            if (AppConfigInfo.PAY_CHANNEL_ZFB.equals(payChannel)) {
                                handlerZfbPay(activity, goodsEntity, token);
                            } else if (AppConfigInfo.PAY_CHANNEL_WECHAT.equals(payChannel)) {
                                handlerWxPay(activity, goodsEntity, token);
                            }
                        }
                        signStatus.postValue(data);
                    }

                    @Override
                    public void onFailed(String error) {
                        showToast(error);
                        hideLoading();
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading();
                    }
                });
    }

    private void handlerWxPay(Activity activity, GoodsEntity currentGood, String token) {
        if (currentGood != null) {
            if (currentGood.getVip_type() > 100) {
                showToast("订阅类商品暂时只支持支付宝付款！");
            } else {
                goWxPay(activity, currentGood, token);
            }
        }
    }


    private void handlerZfbPay(Activity activity, GoodsEntity currentGood, String token) {
        if (currentGood != null) {
            if (currentGood.getVip_type() > 100) {
                preZfbSubscribeOrder(activity, currentGood, token);
            } else {
                goZfbPay(activity, currentGood, token);
            }
        }
    }

    /**
     * 处理支付宝周期扣款回调 先签约后代扣场景
     *
     * @param intent
     */
    public void handlerZfbSubscribeResult(Intent intent, Activity activity, GoodsEntity currentGood) {
        if (ZfbSubscribeCheckUtil.isPayScheme(intent)) {
            showLoading("订单检查中...");
            if (ZfbSubscribeCheckUtil.isPaySuccess(intent)) {
                Observable.timer(1000, TimeUnit.MILLISECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Long>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(Long aLong) {
                                hideLoading();
                                if (currentGood != null) {
                                    updateUserInfo((LifecycleOwner) activity, currentGood);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading();
                            }

                            @Override
                            public void onComplete() {

                            }
                        });
            } else {
                //支付失败
                showToast("自动续费订阅失败！");
            }
        }
    }


    /**
     * 注册用户的接口,注册成功后会自动关闭界面
     *
     * @param owner
     * @param phone
     * @param passWord
     * @param confirmPhone
     * @param confirmPwd
     */
    public void register(LifecycleOwner owner, String phone, String passWord, String confirmPhone, String confirmPwd) {
        RequestInfoModel.register(owner, phone, passWord, confirmPhone, confirmPwd,
                new BaseCallBackListener<UserInfoEntity>() {
                    @Override
                    public void onSuccess(UserInfoEntity data) {
                        hideLoading();
                        showToast("注册成功");
                        BaseApplication.getApplication().onRegister();
                        UserInfoUtils.getInstance().saveUserInfoToLocal(data);
                        UmEventUtils.onEvent(UmEventConstant.register_count);
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.REGISTER_SUCCESS, data));
                        registerSuccess.postValue(data);
                        finishActivity();
                    }

                    @Override
                    public void onFailed(String error) {
                        hideLoading();
                        showToast(error);

                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading("注册中...");
                    }
                });

    }

    /**
     * 传递过来的需要跳转到vip页面参数的值 type的值等于这个才跳转到vip开通页面
     */
    private static final String NEED_TO_VIP = "needToVip";

    /**
     * 用户手机号登录
     *
     * @param owner
     * @param needType 此参数用来判断是否需要跳转到vip页面
     * @param phone
     * @param passWord
     */
    public void loginByPhone(LifecycleOwner owner, String needType, String phone, String passWord) {
        RequestInfoModel.login(owner, phone.trim(), passWord.trim(),
                new BaseCallBackListener<UserInfoEntity>() {
                    @Override
                    public void onSuccess(UserInfoEntity data) {
                        showToast("登录成功");
                        hideLoading();
                        if (uploadCallback != null) {
                            uploadCallback.upload();
                        }
                        handlerLoginSuccess(data, needType);
                    }

                    @Override
                    public void onFailed(String error) {
                        hideLoading();
                        showToast(error);
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading("登录中...");
                    }
                });
    }

    private void handlerLoginSuccess(UserInfoEntity data, String needType) {
        UserInfoUtils.getInstance().saveUserInfoToLocal(data);
        LogUtils.json(data);
        EventBus.getDefault().post(new EventEntity(EventBusConstants.LOGIN_SUCCESS, data));
        if (!TextUtils.isEmpty(needType) && NEED_TO_VIP.equals(needType)) {
            //从评论对话框来的需要跳转至购买页面
            if (!UserInfoUtils.getInstance().isVip()) {
                RouteUtils.routeToOpenVip();
            }
        }

        //如果是vip并且没有绑定或者激活手机号，则在每次登陆后都要提示绑定或激活手机号
        UserInfoUtils.getInstance().checkOrBindPhone();
        finishActivity();
    }

    public void wxLogin(Activity activity, String needType) {
        if (activity == null) {
            return;
        }
        if (!CommonUtils.isWeixinAvilible(activity)) {
            showToast("请先安装微信客户端！");
            return;
        }
        //防止因为有两个微信 弹出选择微信的弹窗后取消选择，无法收到这个系统弹窗的回调，
        // 所以不在一开始就展示loading对话框，登微信授权成功后在显示loading框。
        // 前面通过控制按钮不能点击来限制用户多次点击
        UMShareAPI umShareAPI = UMShareAPI.get(activity);
        umShareAPI.getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                try {
                    showLoading();
                    String unionId = map.get("uid");
                    String accessToken = map.get("accessToken");
                    RequestInfoModel.thirdWechatLogin((LifecycleOwner) activity, unionId, accessToken, new BaseCallBackListener<UserInfoEntity>() {
                        @Override
                        public void onSuccess(UserInfoEntity data) {
                            hideLoading();
                            showToast("第三方登录成功");
                            if (uploadCallback != null) {
                                uploadCallback.upload();
                            }
                            BaseApplication.getApplication().onRegister();
                            handlerLoginSuccess(data, needType);
                        }

                        @Override
                        public void onFailed(String error) {
                            hideLoading();
                        }

                        @Override
                        public void onHandlerStart() {

                        }
                    });

                } catch (Exception e) {
                    hideLoading();
                    showToast("登录失败");
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                LogUtils.d("登录失败：" + throwable.toString());
                hideLoading();
                showToast("登录失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                hideLoading();
                showToast("取消授权登录");
            }
        });

    }

    /**
     * 注销时校验微信 需要获取对应的参数
     *
     * @param activity
     */
    public void verificationWxToLogOut(AppCompatActivity activity) {
        if (activity == null) {
            return;
        }
        if (!CommonUtils.isWeixinAvilible(activity)) {
            showToast("请先安装微信客户端！");
            return;
        }
        showLoading("注销中...");
        UMShareAPI umShareAPI = UMShareAPI.get(activity);
        umShareAPI.getPlatformInfo(activity, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                try {
                    String unionId = map.get("uid");
                    String accessToken = map.get("accessToken");
                    logoutThirdAccount(activity, UserInfoUtils.getInstance().getUserInfoEntity().getToken(), unionId, accessToken);
                } catch (Exception e) {
                    hideLoading();
                    LogUtils.e("登录异常：" + e.toString());
                    showToast("登录失败");
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                LogUtils.d("登录失败：" + throwable.toString());
                hideLoading();
                showToast("登录失败");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                hideLoading();
                showToast("取消授权登录");
            }
        });

    }


    /**
     * 检测手机号是否注册
     *
     * @param owner
     * @param phone
     */
    public void checkPhoneIsRegister(LifecycleOwner owner, String phone) {
        RequestInfoModel.checkAccount(owner, phone, new BaseCallBackListener<Boolean>() {
            @Override
            public void onSuccess(Boolean data) {
                hideLoading();
                LogUtils.d("当前是否注册：" + data);
                phoneIsRegister.postValue(data);
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("查询中...");
            }
        });
    }


    /**
     * 获取验证码
     *
     * @param owner
     * @param phone
     */
    public void getVerificationCode(LifecycleOwner owner, String phone) {
        RequestInfoModel.getVerificationCode(owner, phone.trim(), new BaseCallBackListener<String>() {
            @Override
            public void onSuccess(String data) {
                startCountDownTime();
                hideLoading();
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("验证码发送中...");
            }
        });
    }

    private Disposable downTimeDisposable;

    //验证码倒计时的秒数
    private int COUNT_DOWN_TIME = 60;

    private void cancelDownTime() {
        if (downTimeDisposable != null) {
            downTimeDisposable.dispose();
        }
    }

    /**
     * 开始验证码倒计时
     */
    private void startCountDownTime() {
        cancelDownTime();
        COUNT_DOWN_TIME = 60;
        Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        downTimeDisposable = d;
                    }

                    @Override
                    public void onNext(Long aLong) {
                        COUNT_DOWN_TIME--;
                        verificationCodeTime.postValue(COUNT_DOWN_TIME);
                        if (COUNT_DOWN_TIME == 0) {
                            cancelDownTime();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    /**
     * 激活手机号
     *
     * @param owner
     * @param token
     * @param phone
     * @param code
     */
    public void activePhone(LifecycleOwner owner, String token, String phone, String code) {
        RequestInfoModel.activePhone(owner, token, phone, code, new TokenErrorBackListener<UserInfoEntity.UserInfoBean>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(UserInfoEntity.UserInfoBean data) {
                showToast("手机号激活成功");
                UserInfoUtils.getInstance().getUserInfoEntity().setUserInfo(data);
                UserInfoUtils.getInstance().saveUserInfoToLocal(UserInfoUtils.getInstance().getUserInfoEntity());
                hideLoading();
                finishActivity();
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("激活中...");
            }
        });
    }


    /**
     * 绑定手机号
     *
     * @param owner
     * @param token
     * @param phone
     * @param code
     */
    public void bindPhone(LifecycleOwner owner, String token, String phone, String code, String pwd) {
        RequestInfoModel.bindPhone(owner, token, phone, code, pwd, new TokenErrorBackListener<UserInfoEntity.UserInfoBean.VipInfoBean>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(UserInfoEntity.UserInfoBean.VipInfoBean data) {
                showToast("手机号绑定成功");
                UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().setVip_info(data);
                UserInfoUtils.getInstance().getUserInfoEntity().getUserInfo().setPhone_active(true);
                UserInfoUtils.getInstance().saveUserInfoToLocal(UserInfoUtils.getInstance().getUserInfoEntity());
                hideLoading();
                finishActivity();
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("绑定中...");
            }
        });
    }

    /**
     * 注销账号
     *
     * @param owner
     * @param token
     * @param userId
     * @param phone
     * @param verificationCode
     */
    public void deleteAccount(LifecycleOwner owner, String token, int userId, String phone, String verificationCode) {
        RequestInfoModel.deleteUser(owner, token, userId, phone, verificationCode, new TokenErrorBackListener<String>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(String data) {
//                showToast("账户注销成功！");
                UserInfoUtils.getInstance().clearLoginInfo();
                EventBus.getDefault().post(new EventEntity(EventBusConstants.DELETE_USER, null));
                hideLoading();
                finishActivity();
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("密码修改中...");
            }
        });
    }


    /**
     * 修改用户的密码
     *
     * @param owner
     * @param phone
     * @param passWord
     * @param confirmPwd
     * @param code
     */
    public void editPassWord(LifecycleOwner owner, String phone, String passWord, String confirmPwd, String code) {
        RequestInfoModel.editPassword(owner, phone, passWord, confirmPwd, code, new BaseCallBackListener<UserInfoEntity>() {
            @Override
            public void onSuccess(UserInfoEntity data) {
                showToast("密码修改成功！");
                hideLoading();
                editPasswordSuccess.postValue(data);
                finishActivity();
            }

            @Override
            public void onFailed(String error) {
                showToast(error);
                hideLoading();
            }

            @Override
            public void onHandlerStart() {
                showLoading("密码修改中...");
            }
        });

    }


    /**
     * 通过token去获取用户的信息
     *
     * @param owner
     * @param token
     */
    public void getUserInfo(LifecycleOwner owner, String token) {
        RequestInfoModel.getUserInfo(owner, token, new TokenErrorBackListener<UserInfoEntity.UserInfoBean>() {
            @Override
            public void tokenError(int code, String error) {
                handlerTokenError();
            }

            @Override
            public void onSuccess(UserInfoEntity.UserInfoBean data) {
                hideLoading();
                UserInfoEntity userInfoEntity = UserInfoUtils.getInstance().getUserInfoEntity();
                if (null == userInfoEntity) {
                    userInfoEntity = new UserInfoEntity();
                    userInfoEntity.setToken(RequestInfoModel.bindUserToken);
                }
                userInfoEntity.setUserInfo(data);
                UserInfoUtils.getInstance().setUserInfoEntity(userInfoEntity);
                UserInfoUtils.getInstance().saveUserInfoToLocal(UserInfoUtils.getInstance().getUserInfoEntity());
                userInfoGetSuccess.postValue(UserInfoUtils.getInstance().getUserInfoEntity());
            }

            @Override
            public void onFailed(String error) {
                hideLoading();
                userInfoGetSuccess.postValue(UserInfoUtils.getInstance().getUserInfoEntity());
            }

            @Override
            public void onHandlerStart() {
                showLoading("信息获取中...");
            }
        });
    }


    /**
     * @param context
     * @param authKey               授权的key
     * @param isHidePrivacyCheckBox 是否隐藏一键登录授权页的隐私协议勾选框
     */
    public void initOneKeyLogin(Application context, String authKey, boolean isHidePrivacyCheckBox) {
        if (TextUtils.isEmpty(authKey)) {
            return;
        }
        if (authKey.startsWith("xxxx")) {
            return;
        }
        oneKeyLoginUtils = new OneKeyLoginUtils(context, authKey, isHidePrivacyCheckBox);
        oneKeyLoginUtils.setLoadingListener(new OneKeyLoginUtils.LoadingListener() {
            @Override
            public void showLoadingView(@NotNull String content) {
                showLoading(content);
            }

            @Override
            public void hideLoadingView() {
                hideLoading();
            }
        });
        oneKeyLoginUtils.setAuthTokenListener(new OneKeyLoginUtils.AuthTokenListener() {
            @Override
            public void authTokenSuccess(@NotNull String accessToken) {
                oneKeyLoginAuthSuccess.postValue(accessToken);
            }

            @Override
            public void clickOtherLogin() {
                //点击了其他登录方式 需要跳转其他页面就使用

            }
        });
    }

    public void destroyOneKeyLogin() {
        if (oneKeyLoginUtils != null) {
            oneKeyLoginUtils.destroyOneKeyLogin();
        }
    }

    /**
     * 检查一键登录环境是否可以用
     */
    public void checkOneKeyLoginEnv() {
        if (oneKeyLoginUtils != null) {
            oneKeyLoginUtils.checkOneKeyLoginEnv();
        }
    }

    /**
     * 通过阿里云登录后的token进行登录我们服务器
     *
     * @param owner
     * @param accessToken
     * @param needType
     */
    public void loginByAccessToken(LifecycleOwner owner, String accessToken, String needType) {
        RequestInfoModel.oneKeyLogin(owner, accessToken,
                new BaseCallBackListener<UserInfoEntity>() {
                    @Override
                    public void onSuccess(UserInfoEntity data) {
                        showToast("登录成功");
                        destroyOneKeyLogin();
                        hideLoading();
                        if (uploadCallback != null) {
                            uploadCallback.upload();
                        }
                        BaseApplication.getApplication().onRegister();
                        handlerLoginSuccess(data, needType);
                    }

                    @Override
                    public void onFailed(String error) {
                        hideLoading();
                        showToast(error);
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading("登录中...");
                    }
                });
    }


    /**
     * 解绑第三方账户
     *
     * @param owner
     * @param token
     */
    public void unBindThirdAccount(LifecycleOwner owner, String token) {
        RequestInfoModel.unbindThirdAccount(owner, token,
                new TokenErrorBackListener<String>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(String data) {
                        showToast("账户解绑成功！");
                        UserInfoUtils.getInstance().clearLoginInfo();
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.DELETE_USER, null));
                        hideLoading();
                        finishActivity();
                    }

                    @Override
                    public void onFailed(String error) {
                        hideLoading();
                        showToast(error);
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading("解绑中...");
                    }
                });
    }


    public void logoutThirdAccount(LifecycleOwner owner, String token, String wxUid, String wxToken) {
        RequestInfoModel.logoutWxAccount(owner, wxUid, wxToken, token,
                new TokenErrorBackListener<String>() {
                    @Override
                    public void tokenError(int code, String error) {
                        handlerTokenError();
                    }

                    @Override
                    public void onSuccess(String data) {
//                        showToast("账户注销成功！");
                        UserInfoUtils.getInstance().clearLoginInfo();
                        EventBus.getDefault().post(new EventEntity(EventBusConstants.DELETE_USER, null));
                        hideLoading();
                        finishActivity();
                    }

                    @Override
                    public void onFailed(String error) {
                        hideLoading();
                        showToast(error);
                    }

                    @Override
                    public void onHandlerStart() {
                        showLoading("注销中...");
                    }
                });
    }

    public void handleH5Pay(String h5_url, String referer) {

        System.out.println("h5pay============1" + h5_url);
        WebView webView = new WebView(BaseApplication.getApplication());
        WebSettings wSet = webView.getSettings();
        wSet.setJavaScriptEnabled(true);
        Map map = new HashMap<>();
        map.put("Referer", referer);
        WebSettings webSettings = webView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);  //支持js
        webSettings.setSupportZoom(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setVerticalScrollBarEnabled(false);
        webView.setHorizontalScrollBarEnabled(true);
        webView.loadUrl(h5_url, map);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                if (url.startsWith("weixin://") || url.startsWith("alipays://") ||
                        url.startsWith("tel://")) {
                    //类型我目前用到的是微信、支付宝、拨号 三种跳转方式，其他类型自加
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return true;
            }
        });
    }

    private void filterH5Handle(String payChannel) {
        //采用H5支付
        if (SwitchKeyUtils.getWechatPayType() == SwitchKeyConstants.WECHAT_PAY_TYPE_H5
                && AppConfigInfo.PAY_CHANNEL_WECHAT.equals(payChannel)) {
            isH5pay.postValue(true);
        } else {
            isH5pay.postValue(false);
            payOrder.postValue(false);
        }
    }

    /**
     * 检测当前用户是否处于支付宝签约状态中
     */
    public void checkOrderPayActive(LifecycleOwner owner, String orderId) {
        if (UserInfoUtils.getInstance().isLogin() && !TextUtils.isEmpty(orderId)) {
            String token = UserInfoUtils.getInstance().getUserInfoEntity().getToken();
            if (TextUtils.isEmpty(token)) {
                showToast("Token无效");
                handlerTokenError();
            } else {
                RequestInfoModel.checkOrderPayStatus(
                        owner, token, orderId, new TokenErrorBackListener<SignStatusEntity>() {
                            @Override
                            public void tokenError(int code, String error) {
                                handlerTokenError();
                            }

                            @Override
                            public void onSuccess(SignStatusEntity data) {
                                LogUtils.d(data.getStatus());
                                if (data.getStatus() == 200) {
                                    otherStatusData.postValue(new OtherCodeData(PAY_SUCCESS));
                                }
                                //支付取消或成功时置为false 下次支付会被回调
                                payOrder.postValue(false);
                                isH5pay.setValue(false);
                            }

                            @Override
                            public void onFailed(String error) {
                                showToast(error);
                            }

                            @Override
                            public void onHandlerStart() {
                                showLoading("信息获取中...");
                            }
                        }
                );
            }
        }
    }

    public UploadCallback getUploadCallback() {
        return uploadCallback;
    }

    public void setUploadCallback(UploadCallback uploadCallback) {
        this.uploadCallback = uploadCallback;
    }
}
